package logic

import (
	"context"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/app/jwtx"
	"xialou_platform/app/respx"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WxMiniLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWxMiniLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) WxMiniLoginLogic {
	return WxMiniLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WxMiniLoginLogic) WxMiniLogin(req *types.WxMiniLoginReq) (resp *types.LoginResp, err error) {
	auth := l.svcCtx.WxMiniProgram.GetAuth()
	result, err := auth.Code2Session(req.JsCode)
	if err != nil || result.ErrCode != 0 || result.OpenID == "" {
		return nil, errorx.NewReasonError("微信授权失败", err.Error())
	}
	logx.Infof("微信登陆：%v", result)
	encryptor := l.svcCtx.WxMiniProgram.GetEncryptor()
	plain, err := encryptor.Decrypt(result.SessionKey, req.EncryptedData, req.Iv)
	if err != nil {
		return nil, errorx.NewReasonError("授权手机号失败", err.Error())
	}
	logx.Infof("用户信息：%v", plain)
	agent, err := l.svcCtx.AgentRpc.AgentByPhone(l.ctx, &agentClient.AgentByPhoneReq{Phone: plain.PhoneNumber})
	if err != nil {
		idBody, err := l.svcCtx.AgentRpc.AgentAdd(l.ctx, &agentClient.AgentParam{
			Phone:     plain.PhoneNumber,
			Avatar:    plain.AvatarURL,
			UnionId:   result.UnionID,
			OpenId:    result.OpenID,
			ParentUid: respx.IDParse(req.ParentUid).GetInt64(),
		})
		if err != nil {
			return nil, err
		}
		agent = &agentClient.AgentParam{Id: idBody.Id}
	}
	now := time.Now().Unix()

	accessExpire := l.svcCtx.Config.Auth.AccessExpire

	accessToken, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, agent.Id, agent.Id)

	if err != nil {
		return nil, err
	}

	resp = &types.LoginResp{
		AccessToken:  accessToken,
		AccessExpire: now + accessExpire,
	}
	return resp, nil
}
